# -*- coding: utf-8 -*-

import os
import shutil


class Node(object):
    def __init__(self, image_path, label_file_path):
        assert isinstance(image_path, str) and os.path.exists(image_path)
        assert isinstance(label_file_path, str) and os.path.exists(label_file_path)
        self.image_path = image_path
        self.label_file_path = label_file_path


class Stack(object):
    def __init__(self, folder):
        self.container = list()
        assert isinstance(folder, str) and os.path.isdir(folder)
        self.folder = folder
        images_name = [name for name in os.listdir(folder) if "jpg" in name]
        for image_name in images_name[::-1]:
            image_path = os.path.join(folder, image_name)
            label_file_path = os.path.join(folder, image_name.replace("jpg", "txt"))
            if not os.path.exists(label_file_path):
                with open(label_file_path, "w"):
                    pass
            node = Node(image_path, label_file_path)
            self.container.append(node)

    def push(self, node):
        assert isinstance(node, Node)
        new_image_path = os.path.join(self.folder, os.path.basename(node.image_path))
        new_label_file_path = os.path.join(self.folder, os.path.basename(node.label_file_path))
        shutil.move(node.image_path, new_image_path)
        shutil.move(node.label_file_path, new_label_file_path)
        new_node = Node(new_image_path, new_label_file_path)
        self.container.append(new_node)

    def pop(self):
        try:
            node = self.container.pop()
        except IndexError:
            node = None
        return node

    def size(self):
        return len(self.container)


def main():
    src_folder = r"D:\temp\test2"
    dst_folder = r"D:\temp\test"
    src_stack = Stack(src_folder)
    dst_stack = Stack(dst_folder)
    if src_stack.size() > 0:
        dst_stack.push(src_stack.pop())


if __name__ == "__main__":
    main()
